import Vue from 'vue'
import router from './router'
import store from './store'

import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { notification } from 'ant-design-vue'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import base from '@/config/baseUrl'
import { creatFilter } from '@/utils/filter'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['login', 'demo'] // no redirect whitelist
function GetUserInfo (to, from, next) {
  if (store.getters.roles.length === 0) {
    // 登录后提前创建过滤器
    creatFilter()
    store.dispatch('GetInfo')
      .then(() => {
        // 调用 vuex 的 从后端获取用户的路由菜单，动态添加可访问路由表
        store.dispatch('GenerateRoutes').then(() => {
          // 把已获取到的路由菜单加入到路由表中
          router.addRoutes(store.getters.addRouters)
          const redirect = decodeURIComponent(from.query.redirect || to.path)
          if (to.path === redirect) {
            // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
            next({ path: to.path, replace: true })
          } else {
            // 跳转到目的路由
            next({ path: redirect })
          }
        })
      })
      .catch(() => {
        notification.error({
          message: '错误',
          description: '请求用户信息失败，请重试',
          duration: 3
        })
        store.dispatch('Logout').then(() => {
          setTimeout(() => {
            window.location.href = base.baseURL
          }, 2000)
        })
      })
  } else {
    next()
  }
}
// 使用WebSocket监听兄弟系统事件，统一退出登录
var isWebSocket = process.env.NODE_ENV === 'production'
var getWs = false
function onWebSocket (token) {
//   if (!getWs && isWebSocket) {
//     if ('WebSocket' in window) {
//       var ws = new WebSocket(process.env.VUE_APP_MODEL_BASE_WS + token) // 创建WebSocket连接
//       getWs = true
//       ws.onerror = function (e) {
//         // 如果出现连接、处理、接收、发送数据失败的时候触发onerror事件
//         console.log(e.error)
//       }
//       ws.onopen = function () {
//         // 当WebSocket创建成功时，触发onopen事件
//         console.log('open')
//       }
//       ws.onmessage = function (e) {
//         // 当客户端收到服务端发来的消息时，触发onmessage事件，参数e.data包含server传递过来的数据
//         console.log(e)
//         if (e.data == 'logout') {
//           window.location.reload()
//         }
//       }
//       ws.onclose = function (e) {
//         // 当客户端收到服务端发送的关闭连接请求时，触发onclose事件
//         console.log('WebSocket:close', e)
//       }
//     } else {
//       console.log('您的浏览器不支持WebSocket')
//     }
//   }
}
router.beforeEach((to, from, next) => {
  NProgress.start() // start progress bar
  // 在免登录白名单，直接进入
  if (whiteList.includes(to.name) || to.path.indexOf('/downloadByFeign') != -1) {
    next()
    return;
  }


  if(to.query.token){
    var baseUrl = to.query.baseURL || '/'
    sessionStorage.setItem('baseURL', baseUrl)
    onWebSocket(to.query.token)
    store.dispatch('SetToken', to.query.token).then(res => {
      GetUserInfo(to, from, next)
    })
  }else if(Vue.ls.get(ACCESS_TOKEN)){
    onWebSocket(Vue.ls.get(ACCESS_TOKEN))
    GetUserInfo(to, from, next)
  }else{
    window.location.href = base.baseURL
  }

})

router.afterEach(() => {
  NProgress.done() // finish progress bar
})

// import Vue from 'vue'
// import router from './router'
// import store from './store'

// import NProgress from 'nprogress' // progress bar
// import 'nprogress/nprogress.css' // progress bar style
// import { notification } from 'ant-design-vue'
// import { ACCESS_TOKEN } from '@/store/mutation-types'

// NProgress.configure({ showSpinner: false }) // NProgress Configuration

// const whiteList = ['login', 'register', 'registerResult'] // no redirect whitelist

// router.beforeEach((to, from, next) => {
//   NProgress.start() // start progress bar

//   if (Vue.ls.get(ACCESS_TOKEN)) {
//     /* has token */
//     if (to.path === '/user/login') {
//       next({ path: '/dualReferral/rolloutManage/applyReferral' })
//       NProgress.done()
//     } else {
//       if (store.getters.roles.length === 0) {
//         store.dispatch('GetInfo')
//           .then(() => {
//             // 调用 vuex 的 从后端获取用户的路由菜单，动态添加可访问路由表
//             store.dispatch('GenerateRoutes').then(() => {
//               // 把已获取到的路由菜单加入到路由表中
//               router.addRoutes(store.getters.addRouters)
//               const redirect = decodeURIComponent(from.query.redirect || to.path)
//               if (to.path === redirect) {
//                 // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
//                 next({ ...to, replace: true })
//               } else {
//                 // 跳转到目的路由
//                 next({ path: redirect })
//               }
//             })
//           })
//           .catch(() => {
//             notification.error({
//               message: '错误',
//               description: '请求用户信息失败，请重试'
//             })
//             store.dispatch('Logout').then(() => {
//               next({ path: '/user/login', query: { redirect: to.fullPath } })
//             })
//           })
//       } else {
//         next()
//       }
//     }
//   } else {
//     if (whiteList.includes(to.name)) {
//       // 在免登录白名单，直接进入
//       next()
//     } else {
//       next({ path: '/user/login', query: { redirect: to.fullPath } })
//       NProgress.done() // if current page is login will not trigger afterEach hook, so manually handle it
//     }
//   }
// })

// router.afterEach(() => {
//   NProgress.done() // finish progress bar
// })
